#!/bin/bash

[ ${#@} -lt 4 ] && exit 0

BaseDir=$(readlink -e $1) # $1 PrjBase 和 RtkBase 的共同父目录
PrjBase=$(readlink -e $2) # $2 项目目录
RtkBase=$(readlink -e $3) # $3 RTK 目录
OutputFile_1=$4           # $4 autoconf.mk 的输出文件
OutputFile_2=$(dirname ${OutputFile_1})/autoconf.h # autoconf.h 的输出文件
ConfFile=${@:5} # .conf 的文件列表


#################################################################
# 建立 OutputFile_1 和 OutputFile_2 文件并生成头信息
# OutputFile_1 最终将对应 autoconf.mk
# OutputFile_2 最终将对应 autoconf.h
#################################################################

[ ! -d $(dirname ${OutputFile_1}) ] && !(mkdir -p $(dirname ${OutputFile_1})) && exit 1

echo "\
#
# Automatically generated file by $(basename ${BASH_SOURCE}).
# Do not edit!
#
" > ${OutputFile_1}

echo "\
#pragma once

#ifdef __cplusplus
extern \"C\"
{
#endif
" > ${OutputFile_2}


#################################################################
# 添加 export CONFIG... 到 OutputFile_1 并检查重复
# 添加 #define CONFIG... 到 OutputFile_2
#################################################################

unset Symbols_Redef
ErrorFlag=n

for File in ${ConfFile}; do
	if [ ! -f $File ]; then
		echo -e "  \033[33mwarn\033[0m: No such file of '$File'"
	else
		echo -e "  MERGE   \033[33m$(basename $File)\033[0m"

		echo -e "\n# ${File#*${BaseDir}/}">> ${OutputFile_1}
		sed \
		-e 's/#.*//g' \
		-e 's/\r//g' \
		-e 's/?=//g' \
		-e 's/:=//g' \
		-e 's/+=//g' \
		-e 's/^[ \t]*//g' \
		-e 's/[ \t]*$//g' \
		\
		-e 's/[ \t]*=[ \t]*/=/g' \
		\
		-e 's/=N$/=n/g' \
		-e 's/=Y$/=y/g' \
		\
		-e "s/=\"/='/g" \
		-e "s/\"$/'/g" \
		\
		-n -e '/^[A-Z,a-z,_]*[.,A-Z,a-z,0-9,_,\-]*=.*/p' \
		$File \
		| sed \
		-e 's/=/ = /g' \
		-e 's/[ \t]*$//g' \
		-e 's/^/export /g' \
		>> ${OutputFile_1}
		echo >> ${OutputFile_1}

		## 生成 aoutconf.h
		sed \
		-e 's/#.*//g' \
		-e 's/\r//g' \
		-e 's/?=//g' \
		-e 's/:=//g' \
		-e 's/+=//g' \
		-e 's/^[ \t]*//g' \
		-e 's/[ \t]*$//g' \
		\
		-e 's/[ \t]*=[ \t]*/=/g' \
		\
		-e 's/=n$//g' \
		-e 's/=N$//g' \
		-e 's/=Y$/=y/g' \
		-e 's/=y$/=1/g' \
		\
		-n -e '/^[A-Z,a-z,_]*[A-Z,a-z,0-9,_]*=.*/p' \
		$File \
		| sed \
		-e 's/=/ /g' \
		-e 's/[ \t]*$//g' \
		-e 's/^/#define &/g' \
		>> ${OutputFile_2}
	fi

	unset Symbols_Valid
	for tmp in $(sed -e 's/\r//g' -n -e '/^export /p' ${OutputFile_1} | sed -e 's/^export //g' -e 's/ //g'); do
		if (echo " ${Symbols_Valid} " | grep -q -e " ${tmp%=*}=") && !(echo " ${Symbols_Valid} " | grep -q -e " ${tmp}"); then
			if !(echo "${Symbols_Redef} " | grep -q -e "${tmp} "); then
				echo -e "${File}: \033[31merror\033[0m: redefinition of '${tmp}'"
				Symbols_Redef="${tmp} ${Symbols_Redef}"
			fi
			ErrorFlag=y
		fi
		Symbols_Valid="${tmp} ${Symbols_Valid}"
	done
done

echo "
#ifdef __cplusplus
}
#endif" >> ${OutputFile_2}


[ "${ErrorFlag}" == "y" ] && {
	rm -rf ${OutputFile_1} ${OutputFile_2}
	exit 1
}

#################################################################
# 添加 include $(COMMON_PATH)/... 到 OutputFile_1
#################################################################

echo -e "  GEN     \033[33m$(basename ${OutputFile_1})\033[0m"

unset VAR_Y
unset VAR_N

unset FILE_Y_PRJ
unset DIR_N_PRJ

unset FILE_Y_SUB
unset DIR_N_SUB

unset FILE_Y_LIB
unset DIR_N_LIB


# 功能：在目标目录下查找所有不包含空格的子目录，并按目录深度排序；
#       同时可指定排除的目录，排除规则如下：
#         1. 如果排除目录是绝对路径并且是目标目录的父目录（或祖先目录），则忽略这一排除项；
#         2. 如果排除目录是绝对路径并且不是目标目录的父目录，则排除它及它的所有子目录；
#         3. 如果排除目录是相对路径，则在结果中排除所有包含该目录名称的路径及其子目录。
#
# 使用示例：
#   fast_find_sorted_dirs "/path/to/base" "/parent/of/base" ".git" "build" "/abs/path/exclude"
function fast_find_sorted_dirs() {
	local base_dir
	base_dir="$(realpath "${1:-.}")"
	[[ ! -d "${base_dir}" ]] && return 1

	local -a exclude_patterns=()
	shift

	for excl in "$@"; do
		# 若是绝对路径排除项
		if [[ "${excl}" = /* ]]; then
			local excl_abs
			excl_abs="$(realpath "${excl}")"
			# 规则1：如果排除目录是目标目录的父目录或祖先，则忽略该排除项
			if [[ "${base_dir}" == "${excl_abs}" || "${base_dir}" == "${excl_abs}/"* ]]; then
				continue
			fi
			# 规则2：否则，排除此绝对路径及其子目录
			exclude_patterns+=("-not -path '${excl_abs}'" "-not -path '${excl_abs}/*'")
		else
			# 规则3：对于相对路径，排除所有包含该相对目录名称的路径及其子目录
			exclude_patterns+=("-not -path '*/${excl}'" "-not -path '*/${excl}/*'")
		fi
	done

	# 新增规则：排除所有以 . 开头的目录
	local cmd="find '${base_dir}' -type d ! -name '* *' -not -path '*/.*'"
	for pattern in "${exclude_patterns[@]}"; do
		cmd+=" ${pattern}"
	done
	cmd+=" -printf '%d %p\n'"

	# 执行查询, 按目录深度排序并输出路径（去除深度数）
	eval "${cmd}" | sort -n | cut -d' ' -f2-
}

#################################################################

# VAR_Y, VAR_N: 在 OutputFile_1 中找到所有 export MIX_* = y 和 MIX_ CONFIG_* = n 的变量名
VAR_Y=($(sed -e 's/\r//g' -n -e '/^[ ]*export [_]*MIX_.* = y/p' ${OutputFile_1} | awk '{print $2}'))
VAR_N=($(sed -e 's/\r//g' -n -e '/^[ ]*export [_]*MIX_.* = n/p' ${OutputFile_1} | awk '{print $2}'))


# 按目录深度的顺序找到所有 .prj.mk, .sub.mk 和 .lib.mk 的文件路径
ALL_DIRS="$(fast_find_sorted_dirs ${RtkBase} ${PrjBase} ".git" ".svn" ".vscode" "outdir") $(fast_find_sorted_dirs ${PrjBase} ${RtkBase} ".git" ".svn" ".vscode" "outdir")"
ALL_LIB_MK_FILES_ARRAY=($(find $ALL_DIRS -maxdepth 1 -type f -name "*.lib.mk"))
ALL_SUB_MK_FILES_ARRAY=($(find $ALL_DIRS -maxdepth 1 -type f -name "*.sub.mk"))
ALL_PRJ_MK_FILES_ARRAY=($(find $ALL_DIRS -maxdepth 1 -type f -name "*.prj.mk"))
# 分别记录 .prj.mk, .sub.mk 和 .lib.mk 的文件数
ALL_LIB_MK_FILES_SIZE=${#ALL_LIB_MK_FILES_ARRAY[@]}
ALL_SUB_MK_FILES_SIZE=${#ALL_SUB_MK_FILES_ARRAY[@]}
ALL_PRJ_MK_FILES_SIZE=${#ALL_PRJ_MK_FILES_ARRAY[@]}
# 分离出文件名到 ALL_LIB_MK_BASENAME_ARRAY, ALL_SUB_MK_BASENAME_ARRAY 和 ALL_PRJ_MK_BASENAME_ARRAY 以方便后续处理
ALL_LIB_MK_BASENAME_ARRAY=()
ALL_LIB_MK_DIRNAME_ARRAY=()
ALL_SUB_MK_BASENAME_ARRAY=()
ALL_SUB_MK_DIRNAME_ARRAY=()
ALL_PRJ_MK_BASENAME_ARRAY=()
ALL_PRJ_MK_DIRNAME_ARRAY=()
for tmp in ${ALL_LIB_MK_FILES_ARRAY[@]}; do ALL_LIB_MK_DIRNAME_ARRAY=(${ALL_LIB_MK_DIRNAME_ARRAY[@]} $(dirname ${tmp})); ALL_LIB_MK_BASENAME_ARRAY=(${ALL_LIB_MK_BASENAME_ARRAY[@]} $(basename ${tmp//.lib.mk/})); done
for tmp in ${ALL_SUB_MK_FILES_ARRAY[@]}; do ALL_SUB_MK_DIRNAME_ARRAY=(${ALL_SUB_MK_DIRNAME_ARRAY[@]} $(dirname ${tmp})); ALL_SUB_MK_BASENAME_ARRAY=(${ALL_SUB_MK_BASENAME_ARRAY[@]} $(basename ${tmp//.sub.mk/})); done
for tmp in ${ALL_PRJ_MK_FILES_ARRAY[@]}; do ALL_PRJ_MK_DIRNAME_ARRAY=(${ALL_PRJ_MK_DIRNAME_ARRAY[@]} $(dirname ${tmp})); ALL_PRJ_MK_BASENAME_ARRAY=(${ALL_PRJ_MK_BASENAME_ARRAY[@]} $(basename ${tmp//.prj.mk/})); done

#################################################################

# 按照 VAR_N 的变量名排除，保存到 ALL_LIB_MK_FILES_ARRAY[]
for var_n in ${VAR_N[@]}; do
	for ((i = 0; i < ${#ALL_LIB_MK_BASENAME_ARRAY[@]}; i++)); do
		if [ "${ALL_LIB_MK_BASENAME_ARRAY[i]}" == "${var_n}" ]; then
			DIR_N_LIB=(${DIR_N_LIB[@]} ${ALL_LIB_MK_DIRNAME_ARRAY[i]})
			var_n="${ALL_LIB_MK_DIRNAME_ARRAY[i]}/"
			ALL_LIB_MK_BASENAME_ARRAY[i]="X"
			ALL_LIB_MK_DIRNAME_ARRAY[i]="X"
			ALL_LIB_MK_FILES_ARRAY[i]="X"
			break
		fi
	done
	for ((i++; i < ${#ALL_LIB_MK_DIRNAME_ARRAY[@]}; i++)); do
		if (echo "${ALL_LIB_MK_DIRNAME_ARRAY[i]}" | grep -q -e "^${var_n}"); then
			ALL_LIB_MK_BASENAME_ARRAY[i]="X"
			ALL_LIB_MK_DIRNAME_ARRAY[i]="X"
			ALL_LIB_MK_FILES_ARRAY[i]="X"
		else
			break
		fi
	done
done
# 按照 VAR_Y 的变量名过滤，保存到 ALL_LIB_MK_FILES_ARRAY[]
for ((i = 0; i < ${#ALL_LIB_MK_FILES_ARRAY[@]}; i++)); do
	[ "${ALL_LIB_MK_BASENAME_ARRAY[i]}" == "X" ] || (echo " ${VAR_Y[@]} " | grep -q -e " ${ALL_LIB_MK_BASENAME_ARRAY[i]} ") || {
		ALL_LIB_MK_BASENAME_ARRAY[i]="X"
		ALL_LIB_MK_DIRNAME_ARRAY[i]="X"
		ALL_LIB_MK_FILES_ARRAY[i]="X"
	}
done

#################################################################

# 按照 VAR_N 的变量名排除，保存到 ALL_SUB_MK_FILES_ARRAY[]
for var_n in ${VAR_N[@]}; do
	for ((i = 0; i < ${#ALL_SUB_MK_BASENAME_ARRAY[@]}; i++)); do
		if [ "${ALL_SUB_MK_BASENAME_ARRAY[i]}" == "${var_n}" ]; then
			DIR_N_SUB=(${DIR_N_SUB[@]} ${ALL_SUB_MK_DIRNAME_ARRAY[i]})
			var_n="${ALL_SUB_MK_DIRNAME_ARRAY[i]}/"
			ALL_SUB_MK_BASENAME_ARRAY[i]="X"
			ALL_SUB_MK_DIRNAME_ARRAY[i]="X"
			ALL_SUB_MK_FILES_ARRAY[i]="X"
			break
		fi
	done
	for ((i++; i < ${#ALL_SUB_MK_DIRNAME_ARRAY[@]}; i++)); do
		if (echo "${ALL_SUB_MK_DIRNAME_ARRAY[i]}" | grep -q -e "^${var_n}"); then
			ALL_SUB_MK_BASENAME_ARRAY[i]="X"
			ALL_SUB_MK_DIRNAME_ARRAY[i]="X"
			ALL_SUB_MK_FILES_ARRAY[i]="X"
		else
			break
		fi
	done
done
# 按照 VAR_Y 的变量名过滤，保存到 ALL_SUB_MK_FILES_ARRAY[]
for ((i = 0; i < ${#ALL_SUB_MK_FILES_ARRAY[@]}; i++)); do
	[ "${ALL_SUB_MK_BASENAME_ARRAY[i]}" == "X" ] || (echo " ${VAR_Y[@]} " | grep -q -e " ${ALL_SUB_MK_BASENAME_ARRAY[i]} ") || {
		ALL_SUB_MK_BASENAME_ARRAY[i]="X"
		ALL_SUB_MK_DIRNAME_ARRAY[i]="X"
		ALL_SUB_MK_FILES_ARRAY[i]="X"
	}
done

#################################################################

# 按照 VAR_N 的变量名排除，保存到 ALL_PRJ_MK_FILES_ARRAY[]
for var_n in ${VAR_N[@]}; do
	for ((i = 0; i < ${#ALL_PRJ_MK_BASENAME_ARRAY[@]}; i++)); do
		if [ "${ALL_PRJ_MK_BASENAME_ARRAY[i]}" == "${var_n}" ]; then
			DIR_N_PRJ=(${DIR_N_PRJ[@]} ${ALL_PRJ_MK_DIRNAME_ARRAY[i]})
			var_n="${ALL_PRJ_MK_DIRNAME_ARRAY[i]}/"
			ALL_PRJ_MK_BASENAME_ARRAY[i]="X"
			ALL_PRJ_MK_DIRNAME_ARRAY[i]="X"
			ALL_PRJ_MK_FILES_ARRAY[i]="X"
			break
		fi
	done
	for ((i++; i < ${#ALL_PRJ_MK_DIRNAME_ARRAY[@]}; i++)); do
		if (echo "${ALL_PRJ_MK_DIRNAME_ARRAY[i]}" | grep -q -e "^${var_n}"); then
			ALL_PRJ_MK_BASENAME_ARRAY[i]="X"
			ALL_PRJ_MK_DIRNAME_ARRAY[i]="X"
			ALL_PRJ_MK_FILES_ARRAY[i]="X"
		else
			break
		fi
	done
done
# 按照 VAR_Y 的变量名过滤，保存到 ALL_PRJ_MK_FILES_ARRAY[]
for ((i = 0; i < ${#ALL_PRJ_MK_FILES_ARRAY[@]}; i++)); do
	[ "${ALL_PRJ_MK_BASENAME_ARRAY[i]}" == "X" ] || (echo " ${VAR_Y[@]} " | grep -q -e " ${ALL_PRJ_MK_BASENAME_ARRAY[i]} ") || {
		ALL_PRJ_MK_BASENAME_ARRAY[i]="X"
		ALL_PRJ_MK_DIRNAME_ARRAY[i]="X"
		ALL_PRJ_MK_FILES_ARRAY[i]="X"
	}
done

#################################################################

# 按照 ALL_LIB_MK_DIRNAME_ARRAY[] 和 ALL_SUB_MK_DIRNAME_ARRAY[] 的变量名排除，保存到 ALL_PRJ_MK_FILES_ARRAY[]
for var_n in ${ALL_LIB_MK_DIRNAME_ARRAY[@]} ${ALL_SUB_MK_DIRNAME_ARRAY[@]}; do
	if [ "${var_n}" != "X" ]; then
		for ((i = 0; i < ${#ALL_PRJ_MK_DIRNAME_ARRAY[@]}; i++)); do
			if [ "${ALL_PRJ_MK_DIRNAME_ARRAY[i]}" == "${var_n}" ]; then
				var_n="${ALL_PRJ_MK_DIRNAME_ARRAY[i]}/"
				ALL_PRJ_MK_BASENAME_ARRAY[i]="X"
				ALL_PRJ_MK_DIRNAME_ARRAY[i]="X"
				ALL_PRJ_MK_FILES_ARRAY[i]="X"
				break
			fi
		done
		for ((i++; i < ${#ALL_PRJ_MK_DIRNAME_ARRAY[@]}; i++)); do
			if (echo "${ALL_PRJ_MK_DIRNAME_ARRAY[i]}" | grep -q -e "^${var_n}"); then
				ALL_PRJ_MK_BASENAME_ARRAY[i]="X"
				ALL_PRJ_MK_DIRNAME_ARRAY[i]="X"
				ALL_PRJ_MK_FILES_ARRAY[i]="X"
			else
				break
			fi
		done
	fi
done

#################################################################

# 输出最终使用的 .prj.mk, .sub.mk 和 .lib.mk 文件路径，保存到 FILE_Y_PRJ, FILE_Y_SUB 和 FILE_Y_LIB
for tmp in ${ALL_PRJ_MK_FILES_ARRAY[@]}; do [ "${tmp}" != "X" ] && FILE_Y_PRJ=(${FILE_Y_PRJ[@]} ${tmp}); done
for tmp in ${ALL_SUB_MK_FILES_ARRAY[@]}; do [ "${tmp}" != "X" ] && FILE_Y_SUB=(${FILE_Y_SUB[@]} ${tmp}); done
for tmp in ${ALL_LIB_MK_FILES_ARRAY[@]}; do [ "${tmp}" != "X" ] && FILE_Y_LIB=(${FILE_Y_LIB[@]} ${tmp}); done

#################################################################

# 整理所有使用的 .prj.mk 文件
for File in ${FILE_Y_PRJ[@]}; do

	# 删除不符合赋值规则的变量定义
	(grep -q \
	-e '^[ \t]*inc-.*:=' \
	-e '^[ \t]*inc-.*?=' \
	-e '^[ \t]*src-.*:=' \
	-e '^[ \t]*src-.*?=' \
	-e '^[ \t]*obj-.*:=' \
	-e '^[ \t]*obj-.*?=' \
	${File}) && \
	sed \
	-e "/^[ \t]*inc-.*:=/d" \
	-e "/^[ \t]*inc-.*?=/d" \
	-e "/^[ \t]*src-.*:=/d" \
	-e "/^[ \t]*src-.*?=/d" \
	-e "/^[ \t]*obj-.*:=/d" \
	-e "/^[ \t]*obj-.*?=/d" \
	-i ${File}

	# 添加默认变量: inc-y 和 src-y
	BaseName=$(basename ${File%.prj.mk*})
	(grep -q -e '^[ ]*inc-.*+=' -e '^[ ]*src-.*+=' ${File}) || {
		echo -e "${BaseName}-INC-ALL ?= y\n${BaseName}-SRC-ALL ?= y\n\ninc-\$(${BaseName}-INC-ALL) += *\nsrc-\$(${BaseName}-SRC-ALL) += *\n\nobj-n += " >> ${File}
	}

	# 检查是否有重复的 inc-y 和 src-y
	incy=($(sed -e 's/\r//g' -n -e '/^[ \t]*inc-y.*+=/p' $File | sed -e 's/\r//g' -e 's/^[ ]*inc-y.*+=[ \t]*//g' -e 's/[ \t]$//g'))
	[ ${#incy[@]} -gt 1 ] && echo -e "[\033[33mWARN\033[0m] $File: multiple defined symbol 'inc-y'"
	srcy=($(sed -e 's/\r//g' -n -e '/^[ \t]*src-y.*+=/p' $File | sed -e 's/\r//g' -e 's/^[ ]*src-y.*+=[ \t]*//g' -e 's/[ \t]$//g'))
	[ ${#srcy[@]} -gt 1 ] && echo -e "[\033[33mWARN\033[0m] $File: multiple defined symbol 'src-y'"

done

# 整理所有使用的 .sub.mk 文件
for File in ${FILE_Y_SUB[@]}; do

	# 删除不符合赋值规则的变量定义
	(grep -q \
	-e '^[ \t]*inc-.*:=' \
	-e '^[ \t]*inc-.*?=' \
	-e '^[ \t]*src-.*:=' \
	-e '^[ \t]*src-.*?=' \
	-e '^[ \t]*obj-.*:=' \
	-e '^[ \t]*obj-.*?=' \
	${File}) && \
	sed \
	-e "/^[ \t]*inc-.*:=/d" \
	-e "/^[ \t]*inc-.*?=/d" \
	-e "/^[ \t]*src-.*:=/d" \
	-e "/^[ \t]*src-.*?=/d" \
	-e "/^[ \t]*obj-.*:=/d" \
	-e "/^[ \t]*obj-.*?=/d" \
	-i ${File}

	# 添加默认变量: inc-y 和 src-y
	BaseName=$(basename ${File%.sub.mk*})
	(grep -q -e '^[ ]*inc-.*+=' -e '^[ ]*src-.*+=' ${File}) || {
		echo -e "${BaseName}-INC-ALL ?= y\n${BaseName}-SRC-ALL ?= y\n\ninc-\$(${BaseName}-INC-ALL) += *\nsrc-\$(${BaseName}-SRC-ALL) += *\n\nobj-n += " >> ${File}
	}

	# 检查是否有重复的 inc-y 和 src-y
	incy=($(sed -e 's/\r//g' -n -e '/^[ \t]*inc-y.*+=/p' $File | sed -e 's/\r//g' -e 's/^[ ]*inc-y.*+=[ \t]*//g' -e 's/[ \t]$//g'))
	[ ${#incy[@]} -gt 1 ] && echo -e "[\033[33mWARN\033[0m] $File: multiple defined symbol 'inc-y'"
	srcy=($(sed -e 's/\r//g' -n -e '/^[ \t]*src-y.*+=/p' $File | sed -e 's/\r//g' -e 's/^[ ]*src-y.*+=[ \t]*//g' -e 's/[ \t]$//g'))
	[ ${#srcy[@]} -gt 1 ] && echo -e "[\033[33mWARN\033[0m] $File: multiple defined symbol 'src-y'"

done

#################################################################

# 整理所有使用的 .lib.mk 文件
unset Lib_MK_Array
unset Lib_y_Array
for File in ${FILE_Y_LIB[@]}; do

	# 删除不符合赋值规则的变量定义
	(grep -q \
	-e '^[ \t]*inc-.*:=' \
	-e '^[ \t]*inc-.*?=' \
	-e '^[ \t]*src-.*:=' \
	-e '^[ \t]*src-.*?=' \
	-e '^[ \t]*obj-.*:=' \
	-e '^[ \t]*obj-.*?=' \
	-e '^[ \t]*lib-.*+=' \
	${File}) && \
	sed \
	-e "/^[ \t]*inc-.*:=/d" \
	-e "/^[ \t]*inc-.*?=/d" \
	-e "/^[ \t]*src-.*:=/d" \
	-e "/^[ \t]*src-.*?=/d" \
	-e "/^[ \t]*obj-.*:=/d" \
	-e "/^[ \t]*obj-.*?=/d" \
	-e "/^[ \t]*lib-.*+=/d" \
	-i ${File}

	# 添加默认变量: inc-y 和 src-y
	BaseName=$(basename ${File%.lib.mk*})
	(grep -q -e '^[ ]*inc-.*+=' -e '^[ ]*src-.*+=' ${File}) || {
		echo -e "${BaseName}-INC-ALL ?= y\n${BaseName}-SRC-ALL ?= y\n\ninc-\$(${BaseName}-INC-ALL) += *\nsrc-\$(${BaseName}-SRC-ALL) += *\n\nobj-n += " >> ${File}
	}

	# 添加默认变量: lib-y
	liby=$(sed -e 's/\r//g' -n -e '/^[ ]*lib-.*=[ ]*/p' $File | sed -e 's/\r//g' -e 's/^[ ]*lib-.*=[ ]*//g' -e 's/[ \t]$//g')
	if [ -z "${liby}" ]; then
		Dir=$(dirname ${File#*${BaseDir}\/})
		liby="library/${Dir#*/}/$(basename $(dirname $File)).a"
		echo -e "\nlib-y := ${liby}" >> ${File}
	fi

	# 检查是否有重复的 inc-y 和 src-y
	incy=($(sed -e 's/\r//g' -n -e '/^[ \t]*inc-y.*+=/p' $File | sed -e 's/\r//g' -e 's/^[ ]*inc-y.*+=[ \t]*//g' -e 's/[ \t]$//g'))
	[ ${#incy[@]} -gt 1 ] && echo -e "[\033[33mWARN\033[0m] $File: multiple defined symbol 'inc-y'"
	srcy=($(sed -e 's/\r//g' -n -e '/^[ \t]*src-y.*+=/p' $File | sed -e 's/\r//g' -e 's/^[ ]*src-y.*+=[ \t]*//g' -e 's/[ \t]$//g'))
	[ ${#srcy[@]} -gt 1 ] && echo -e "[\033[33mWARN\033[0m] $File: multiple defined symbol 'src-y'"

	# 确认是否有重复的 lib-y 的变量值
	if (echo " ${Lib_y_Array[@]} " | grep -q -e " ${liby} "); then
		echo -e "${File}: \033[31merror\033[0m: redefinition of lib-y = \033[32m$liby\033[0m."
		echo -e "  This is the location of the previous definition: "
		for ((i = 0; i < ${#Lib_y_Array[@]}; i++)); do
			if [ "${Lib_y_Array[$i]}" == "$liby" ]; then
				echo -e "\033[33m${Lib_MK_Array[$i]}\033[0m"
			fi
		done
		echo
		rm -rf ${OutputFile_1} ${OutputFile_2}
		exit 1
	fi
	Lib_MK_Array=(${Lib_MK_Array[@]} $File)
	Lib_y_Array=(${Lib_y_Array[@]} $liby)
done

#################################################################

# 添加 include $(COMMON_PATH)/... 到 OutputFile_1
echo -e '\n# include makefiles'>> ${OutputFile_1}
echo -e '-include $(MK_FILE_SDK)'>> ${OutputFile_1}
for tmp in ${FILE_Y_PRJ[@]}; do
	echo "-include \$(COMMON_PATH)/${tmp#*${BaseDir}/}" >> ${OutputFile_1}
done
for tmp in ${FILE_Y_SUB[@]}; do
	echo "-include \$(COMMON_PATH)/${tmp#*${BaseDir}/}" >> ${OutputFile_1}
done
for tmp in ${FILE_Y_LIB[@]}; do
	echo "-include \$(COMMON_PATH)/${tmp#*${BaseDir}/}" >> ${OutputFile_1}
done

# 添加变量 PRJ-MK, PRJ-OUT, SUB-MK, SUB-OUT, LIB-MK, LIB-OUT 到 OutputFile_1
echo -e '\n# Module paths'>> ${OutputFile_1}
for tmp in ${FILE_Y_PRJ[@]}; do echo "PRJ-MK += ${tmp#*${BaseDir}/}" >> ${OutputFile_1}; done
for tmp in ${FILE_Y_SUB[@]}; do echo "SUB-MK += ${tmp#*${BaseDir}/}" >> ${OutputFile_1}; done
for tmp in ${FILE_Y_LIB[@]}; do echo "LIB-MK += ${tmp#*${BaseDir}/}" >> ${OutputFile_1}; done
for tmp in ${DIR_N_PRJ[@]}; do echo "PRJ-OUT += ${tmp#*${BaseDir}/}" >> ${OutputFile_1}; done
for tmp in ${DIR_N_SUB[@]}; do echo "SUB-OUT += ${tmp#*${BaseDir}/}" >> ${OutputFile_1}; done
for tmp in ${DIR_N_LIB[@]}; do echo "LIB-OUT += ${tmp#*${BaseDir}/}" >> ${OutputFile_1}; done


#################################################################
# 添加 Project options, Object options 和 Library options 到 OutputFile_1
#################################################################

echo -e '\n# Project options'>> ${OutputFile_1}
for File in ${FILE_Y_PRJ[@]}; do
	for Cmd in $(sed -e 's/\r//g' -e 's/[ \t]*//g' -n -e '/^[ ]*inc-.*+=[ ]*/p' $File); do
		if [ "${Cmd##*/}" == "*" ] || [ "${Cmd##*=}" == "*" ]; then
			Name="PRJ-INC-ALL"
			Cmd=${Cmd%\**}
			Cmd=${Cmd%/*}
		else
			Name="PRJ-INC-DIR"
		fi

		Result=$(dirname ${File})/${Cmd#*+=}
		Cmd=${Cmd%%+=*}
		if [ -d ${Result} ]; then
			Result=$(readlink -e ${Result})
			Cmd="${Name}${Cmd#*inc}"
			Result=${Result#*${BaseDir}\/}
			echo "${Cmd} += ${Result}" >> ${OutputFile_1}
		fi
	done
done
for File in ${FILE_Y_PRJ[@]}; do
	for Cmd in $(sed -e 's/\r//g' -e 's/[ \t]*//g' -n -e '/^[ ]*src-.*+=[ ]*/p' $File); do
		if [ "${Cmd##*/}" == "*" ] || [ "${Cmd##*=}" == "*" ]; then
			Cmd=${Cmd%\**}
			Cmd=${Cmd%/*}
			Result=$(dirname ${File})/${Cmd#*+=}
			Cmd=${Cmd%%+=*}
			Cmd="PRJ-SRC${Cmd#*src}"
			if [ -d ${Result} ]; then
				Result=$(readlink -e ${Result})
				# if [ "${Result}" != "$(readlink -e $(dirname ${File}))" ]; then
				if :; then
					Dir=${Result}
					for Result in $(find ${Dir} -not -path '*/.*' -iname "*.[cs]" -o -not -path '*/.*' -iname "*.asm" -o -not -path '*/.*' -iname "*.cpp" -type f); do
						Result=${Result#*${BaseDir}\/}
						echo "${Cmd} += ${Result}" >> ${OutputFile_1}
					done
				fi
			fi
		else
			Result=$(dirname ${File})/${Cmd#*+=}
			Cmd=${Cmd%%+=*}
			Cmd="PRJ-SRC${Cmd#*src}"
			if [ -f ${Result} ]; then
				Result=$(readlink -e ${Result})
				Result=${Result#*${BaseDir}\/}
				echo "${Cmd} += ${Result}" >> ${OutputFile_1}
			elif [ -d ${Result} ]; then
				Result=$(readlink -e ${Result})
				# if [ "${Result}" != "$(readlink -e $(dirname ${File}))" ]; then
				if :; then
					Dir=${Result}
					for Result in $(find ${Dir} -maxdepth 1 -not -path '*/.*' -iname "*.[cs]" -o -not -path '*/.*' -iname "*.asm" -o -not -path '*/.*' -iname "*.cpp" -type f); do
						Result=${Result#*${BaseDir}\/}
						echo "${Cmd} += ${Result}" >> ${OutputFile_1}
					done
				fi
			fi
		fi
	done
done

echo -e '\n# Submodule options'>> ${OutputFile_1}
for File in ${FILE_Y_SUB[@]}; do
	for Cmd in $(sed -e 's/\r//g' -e 's/[ \t]*//g' -n -e '/^[ ]*inc-.*+=[ ]*/p' $File); do
		if [ "${Cmd##*/}" == "*" ] || [ "${Cmd##*=}" == "*" ]; then
			Name="SUB-INC-ALL"
			Cmd=${Cmd%\**}
			Cmd=${Cmd%/*}
		else
			Name="SUB-INC-DIR"
		fi

		Result=$(dirname ${File})/${Cmd#*+=}
		Cmd=${Cmd%%+=*}
		if [ -d ${Result} ]; then
			Result=$(readlink -e ${Result})
			Cmd="${Name}${Cmd#*inc}"
			Result=${Result#*${BaseDir}\/}
			echo "${Cmd} += ${Result}" >> ${OutputFile_1}
		fi
	done
done
for File in ${FILE_Y_SUB[@]}; do
	for Cmd in $(sed -e 's/\r//g' -e 's/[ \t]*//g' -n -e '/^[ ]*src-.*+=[ ]*/p' $File); do
		if [ "${Cmd##*/}" == "*" ] || [ "${Cmd##*=}" == "*" ]; then
			Cmd=${Cmd%\**}
			Cmd=${Cmd%/*}
			Result=$(dirname ${File})/${Cmd#*+=}
			Cmd=${Cmd%%+=*}
			Cmd="SUB-SRC${Cmd#*src}"
			if [ -d ${Result} ]; then
				Result=$(readlink -e ${Result})
				# if [ "${Result}" != "$(readlink -e $(dirname ${File}))" ]; then
				if :; then
					Dir=${Result}
					for Result in $(find ${Dir} -not -path '*/.*' -iname "*.[cs]" -o -not -path '*/.*' -iname "*.asm" -o -not -path '*/.*' -iname "*.cpp" -type f); do
						Result=${Result#*${BaseDir}\/}
						echo "${Cmd} += ${Result}" >> ${OutputFile_1}
					done
				fi
			fi
		else
			Result=$(dirname ${File})/${Cmd#*+=}
			Cmd=${Cmd%%+=*}
			Cmd="SUB-SRC${Cmd#*src}"
			if [ -f ${Result} ]; then
				Result=$(readlink -e ${Result})
				Result=${Result#*${BaseDir}\/}
				echo "${Cmd} += ${Result}" >> ${OutputFile_1}
			elif [ -d ${Result} ]; then
				Result=$(readlink -e ${Result})
				# if [ "${Result}" != "$(readlink -e $(dirname ${File}))" ]; then
				if :; then
					Dir=${Result}
					for Result in $(find ${Dir} -maxdepth 1 -not -path '*/.*' -iname "*.[cs]" -o -not -path '*/.*' -iname "*.asm" -o -not -path '*/.*' -iname "*.cpp" -type f); do
						Result=${Result#*${BaseDir}\/}
						echo "${Cmd} += ${Result}" >> ${OutputFile_1}
					done
				fi
			fi
		fi
	done
done

echo -e '\n# Library options'>> ${OutputFile_1}
for File in ${FILE_Y_LIB[@]}; do
	for Cmd in $(sed -e 's/\r//g' -e 's/[ \t]*//g' -n -e '/^[ ]*inc-.*+=[ ]*/p' $File); do
		if [ "${Cmd##*/}" == "*" ] || [ "${Cmd##*=}" == "*" ]; then
			Name="LIB-INC-ALL"
			Cmd=${Cmd%\**}
			Cmd=${Cmd%/*}
		else
			Name="LIB-INC-DIR"
		fi

		Result=$(dirname ${File})/${Cmd#*+=}
		Cmd=${Cmd%%+=*}
		if [ -d ${Result} ]; then
			Result=$(readlink -e ${Result})
			Cmd="${Name}${Cmd#*inc}"
			Result=${Result#*${BaseDir}\/}
			echo "${Cmd} += ${Result}" >> ${OutputFile_1}
		fi
	done
done
for File in ${FILE_Y_LIB[@]}; do
	for Cmd in $(sed -e 's/\r//g' -e 's/[ \t]*//g' -n -e '/^[ ]*src-.*+=[ ]*/p' $File); do
		if [ "${Cmd##*/}" == "*" ] || [ "${Cmd##*=}" == "*" ]; then
			Cmd=${Cmd%\**}
			Cmd=${Cmd%/*}
			Result=$(dirname ${File})/${Cmd#*+=}
			Cmd=${Cmd%%+=*}
			Cmd="LIB-SRC${Cmd#*src}"
			if [ -d ${Result} ]; then
				Result=$(readlink -e ${Result})
				# if [ "${Result}" != "$(readlink -e $(dirname ${File}))" ]; then
				if :; then
					Dir=${Result}
					for Result in $(find ${Dir} -not -path '*/.*' -iname "*.[cs]" -o -not -path '*/.*' -iname "*.asm" -o -not -path '*/.*' -iname "*.cpp" -type f); do
						Result=${Result#*${BaseDir}\/}
						echo "${Cmd} += ${Result}" >> ${OutputFile_1}
					done
				fi
			fi
		else
			Result=$(dirname ${File})/${Cmd#*+=}
			Cmd=${Cmd%%+=*}
			Cmd="LIB-SRC${Cmd#*src}"
			if [ -f ${Result} ]; then
				Result=$(readlink -e ${Result})
				Result=${Result#*${BaseDir}\/}
				echo "${Cmd} += ${Result}" >> ${OutputFile_1}
			elif [ -d ${Result} ]; then
				Result=$(readlink -e ${Result})
				# if [ "${Result}" != "$(readlink -e $(dirname ${File}))" ]; then
				if :; then
					Dir=${Result}
					for Result in $(find ${Dir} -maxdepth 1 -not -path '*/.*' -iname "*.[cs]" -o -not -path '*/.*' -iname "*.asm" -o -not -path '*/.*' -iname "*.cpp" -type f); do
						Result=${Result#*${BaseDir}\/}
						echo "${Cmd} += ${Result}" >> ${OutputFile_1}
					done
				fi
			fi
		fi
	done
done

echo -e '\n# Objects filter out'>> ${OutputFile_1}
for File in ${FILE_Y_PRJ[@]} ${FILE_Y_SUB[@]} ${FILE_Y_LIB[@]}; do
	for Cmd in $(sed -e 's/\r//g' -e 's/[ \t]*//g' -n -e '/^[ ]*obj-.*+=[ ]*/p' $File); do
		if [ "${Cmd##*/}" == "*" ] || [ "${Cmd##*=}" == "*" ]; then
			Cmd=${Cmd%\**}
			Cmd=${Cmd%/*}
			Result=$(dirname ${File})/${Cmd#*+=}
			Cmd=${Cmd%%+=*}
			Cmd="OBJS${Cmd#*obj}"
			if [ -d ${Result} ]; then
				Result=$(readlink -e ${Result})
				if [ "${Result}" != "$(readlink -e $(dirname ${File}))" ]; then
					Dir=${Result}
					for Result in $(find ${Dir} -not -path '*/.*' -iname "*.[cs]" -o -not -path '*/.*' -iname "*.asm" -o -not -path '*/.*' -iname "*.cpp" -type f); do
						Result=${Result#*${BaseDir}\/}
						echo "${Cmd} += ${Result}" >> ${OutputFile_1}
					done
				fi
			fi
		else
			Result=$(dirname ${File})/${Cmd#*+=}
			Cmd=${Cmd%%+=*}
			Cmd="OBJS${Cmd#*obj}"
			if [ -f ${Result} ]; then
				Result=$(readlink -e ${Result})
				Result=${Result#*${BaseDir}\/}
				echo "${Cmd} += ${Result}" >> ${OutputFile_1}
			elif [ -d ${Result} ]; then
				Result=$(readlink -e ${Result})
				if [ "${Result}" != "$(readlink -e $(dirname ${File}))" ]; then
					Dir=${Result}
					for Result in $(find ${Dir} -maxdepth 1 -not -path '*/.*' -iname "*.[cs]" -o -not -path '*/.*' -iname "*.asm" -o -not -path '*/.*' -iname "*.cpp" -type f); do
						Result=${Result#*${BaseDir}\/}
						echo "${Cmd} += ${Result}" >> ${OutputFile_1}
					done
				fi
			fi
		fi
	done
done
